//
//  ViewController.m
//  Example13-2
//
//  Created by 孙晓晔 on 2017/4/25.
//  Copyright © 2017年 孙晓晔. All rights reserved.
//

#import "ViewController.h"
#import "DownloadOperation.h"
#import "Download.h"

@interface ViewController ()<DownloadDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *imageView;

@property(nonatomic,strong) NSArray *urlArr;
@property(nonatomic,strong) NSDictionary *imageDict;
@property(nonatomic,assign) int currentPage;

@property(nonatomic,strong) Download *download;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    self.urlArr = @[@"http://pic32.photophoto.cn/20140723/0016028127548336_b.jpg", @"http://pic9.photophoto.cn/20081224/0011024043560328_b.jpg", @"http://pic.qiantucdn.com/58pic/11/84/44/79K58PICWak.jpg",@"http://n.sinaimg.cn/news/20170425/P-HV-fyepsch3269218.jpg", @"http://n.sinaimg.cn/news/1_img/upload/c4b46437/20170413/NORK-fyecrxv5796295.jpg"];
    
    self.download = [[Download alloc]initWithUrl:self.urlArr];
    self.download.delegate = self;

}

// 启动下载线程
- (IBAction)download:(id)sender {
    
    [self.download start:1];
    
    self.currentPage = 0;
}

// 清除内存缓存
- (IBAction)clear:(id)sender {
    
    self.imageDict = [NSDictionary dictionary];
    
    [self.download clear];
}

// 显示图片
- (void)showImage {
    
    NSString *key = self.urlArr[_currentPage];
    
    if ([self.imageDict objectForKey:key]) {
        self.imageView.image = [[UIImage alloc]initWithData:_imageDict[key]];
    }
}

// 上一张
- (IBAction)prev:(id)sender {
    self.currentPage--;
    if (self.currentPage < 0) {
        self.currentPage = (int)[self.urlArr count] - 1;
    }
    
    [self showImage];
}

// 下一张
- (IBAction)next:(id)sender {
    self.currentPage++;
    if (self.currentPage > [self.urlArr count] - 1) {
        self.currentPage = 0;
    }
    
    [self showImage];
}

#pragma mark DownloadDelegate
-(void)didFinishDownload:(NSDictionary *)dict {
    // NSLog(@"全部已下载 = %ld", [dict count]);
    
    self.imageDict = dict;
    
    [self showImage];
}

@end
